<?php

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

function apiResponse($code = 0, $msg = 'success', $data = null): JsonResponse
{
    return response()->json([
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ]);
}

function apiResponseError($arr,$data = null): JsonResponse
{
    return response()->json([
        'code' => $arr[0],
        'msg' => $arr[1],
        'data' => $data
    ]);
}

/**
 * 处理资源路径地址：将网络地址处理成相对地址
 * @param string $path 路径地址
 * @param string $prefix 要处理的地址前缀，如:images/
 * @return string
 */
function normalizePath(string $path,string $prefix='images/'): string
{
    if (str_contains($path, $prefix) && str_starts_with($path, 'http')) {
        $parts = explode($prefix, $path);
        return $prefix . end($parts);
    }
    return $path;
}


/**
 * 生成订单号（默认 21 位）
 * 前缀（2位）+时间（12位）+毫秒（3位）+随机数（4位）
 * 示例（默认4位随机）：前缀+251116201743+512+3487 → 共21位
 */

function generateOrderNumber(string $prefix = '', int $randLength = 4): string
{
    $dateTime = date('ymdHis');
    $micro = microtime();
    list($microSec,) = explode(' ', $micro);
    $milliseconds = sprintf('%03d', $microSec * 1000);
    // 随机数字（可变长度）
    if ($randLength < 1) {
        $randLength = 1;
    }
    $min = (int) str_pad('1', $randLength, '0');
    $max = (int) str_pad('', $randLength, '9');
    $random = random_int($min, $max);
    return $prefix . $dateTime . $milliseconds . $random;
}


/**
 * 生成唯一编码
 * @param string $prefix 前缀
 * @param int $randomLength 随机数长度
 * @param string|null $table 表名
 * @param string|null $column 列名
 * @return string
 */
if (!function_exists('generateUniqueCode')) {
    function generateUniqueCode(string $prefix = '', int $randomLength = 8, ?string $table = null, ?string $column = null): string
    {
        $timePart = date('ymd');
        $maxRand = (int) str_repeat('9', min($randomLength, 9));
        do {
            $randomPart = str_pad(mt_rand(0, $maxRand), $randomLength, '0', STR_PAD_LEFT);
            $code = $prefix . $timePart . $randomPart;
            if (is_null($table) || is_null($column)) {
                return $code;
            }
        } while (\Illuminate\Support\Facades\DB::table($table)->where($column, $code)->exists());
        return $code;
    }
}


/**
 * 通用递归插入父子级数据
 * @param  string  $table
 * @param  array  $categories
 * @param  int|null  $parentId
 * @return void
 */
function insertNestedData(string $table,array $categories, ?int $parentId = null)
{
    $date = date('Y-m-d H:i:s');

    foreach ($categories as $category) {
        // 提取子分类（如果存在）
        $children = $category['children'] ?? [];
        unset($category['children']); // 移除 children 键，避免插入数据库
        // 组装分类基础数据
        $categoryData = array_merge([
            'parent_id'   => $parentId,
            'created_at'  => $date,
            'updated_at'  => $date
        ], $category);
        // 插入一级/当前层级分类，获取自增ID
        $categoryId = DB::table($table)->insertGetId($categoryData);
        // 递归插入子分类（如果有）
        if (!empty($children)) {
            insertNestedData($table,$children, $categoryId);
        }
    }
}
